import sys
import os
import string
import SyntaxParser
import Result
import statistic

def BuildEventDict(filePath):
    try:
        input = open(filePath,'r')
        s = input.readlines()
        events ={}
        
        for line in s:
           event = {}
           event['name'] = str(line).strip()
           event['answers'] = str(line).strip() + '_answers'
           event['path'] = 'dict/realtimedict/realtime_' + str(line).strip() + '_dictionary.txt'
           event['dictionary'] = 'realtime_' + str(line).strip() + '_dictionary'
           
           if str(line).strip() == "patientevents":
              event['conditions'] = None                         
           elif str(line).strip() == "groupevents":
              event['conditions'] = None
           elif str(line).strip() == "categoric_terms":
              event['answers'] = None
              event['path'] = 'dict/realtimedict/realtime_' + str(line).strip() + '.txt'
              event['dictionary'] = None             
              event['conditions'] = None
           else:
              event['conditions'] = str(line).strip() + '_conditions'
           
           events[str(line).strip()] = event
        return events              

    except IOError, (errno, strerror):
        print "I/O error(%s): %s" % (errno, strerror)

def match(result, events, word, stat = None):
    
    term = result.getAttribute()
    event = result.getEventType()
    stat_array = result.getStatEnt()

    if len(stat_array) > 0:
        try:
           if (events[event]['dictionary'][str(word).strip()] == term) and str(stat_array[0]).lower() == str(stat).lower() :
              return simplifyValues(result)
           else:
              return "StatError"
        except KeyError:
           return "KeyError"
    else:
        try:
           if events[event]['dictionary'][str(word).strip()] == term :
              return simplifyValues(result)
           else:
              return "StatError"
        except KeyError:
           return "KeyError"
        

       
def simplifyValues(result):
    new_values = []
    values = result.getValues()
    res_type = result.getEventType()
    stat_array = result.getStatEnt()
    ref_array = result.getRefEnt()
    
    if len(values) > 0:
                if stat_array is not None:
                    for stat in stat_array:
                             if res_type == "groupevents":
                                 numeric_values = SyntaxParser.getValues(values,2)
                             else:
                                 numeric_values = SyntaxParser.getValues(values)
                             for v in numeric_values:
                                 print str(v)

                             if stat == "mean":
                                  value = str(statistic.mean(numeric_values))
                             elif stat == "sd":                                     
                                  value = str(statistic.s_d(numeric_values))
                             elif stat == "median":                                    
                                  value = str(statistic.median(numeric_values))
                             elif stat == "max":                                    
                                  value = str(statistic.maximum(numeric_values))
                             elif stat == "min":                                     
                                  value = str(statistic.minimum(numeric_values))
                             elif stat == "count":            
                                  value = str(statistic.count(numeric_values))
                             elif stat == "sum":
                                  value = str(statistic.sum_(numeric_values))
                             new_values.append(value)        
                                           
                if ref_array is not None:
                    for ref in ref_array:
                        if ref == "all values":                                          
                          if res_type == "patientevents" or res_type == "adtevents":
                             col = 0
                          elif res_type == "groupevents":
                             col = 2
                          else :
                             col = 1
              
                        for n in range(0, len(values)):
                          value = str(values[n]).split(';')
                          try:                                 
                              new_values.append(value[col])
                          except ValueError:
                              continue
                          except IndexError:
                              continue

    return new_values
